package jude.java.money.batch.task;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Parameter;
import jude.java.money.batch.memory.IP;

/**
 * 批量删除文件
 * */
public class BatchIP extends BatchTask<Object> {
	
	private Map<String, Set<String>> all;
	
	public BatchIP(Parameter<Object> p) {
		super(p);
		all = new HashMap<String, Set<String>>();
	}
	
	@Override
	protected void initFlags() {
		super.initFlags();
		removeFlags(Definition.CONFIG_IGNORE);
	}
	
/*
	@Override
	public void run() {
		String[][] sites = Config.Zencart.SITES;
		for (int i = 0; i < sites.length; i++) {
			for (int j = 0; j < sites[i].length; j++) {
				fetch(sites[i][j]);
			}
		}
		sites = Config.Magento.SITES;
		for (int i = 0; i < sites.length; i++) {
			for (int j = 0; j < sites[i].length; j++) {
				fetch(sites[i][j]);
			}
		}
		sites = Config.Wordpress.SITES;
		for (int i = 0; i < sites.length; i++) {
			for (int j = 0; j < sites[i].length; j++) {
				fetch(sites[i][j]);
			}
		}
		for (Map.Entry<String, Set<String>> entry : all.entrySet()) {
			System.out.println("-- " + entry.getKey() + " --");
			for (String domain : entry.getValue()) {
				System.out.println(domain);
			}
			System.out.println();
		}
	}
//*/	
	private void fetch(String domain) {
		if (BatchTask.isConfig(domain))
			return;
		try {
			InetAddress address = InetAddress.getByName(domain);
			put(domain, address.getHostAddress());
		} catch (UnknownHostException e) {
			put(domain, "UnknownHost");
		}
	}
	
	private void put(String domain, String ip) {
//		System.out.println("setIP(\"" + domain + "\", \"" + ip + "\");");
		Set<String> domains = all.get(ip);
		if (domains == null) {
			domains = new HashSet<String>();
			all.put(ip, domains);
		}
		domains.add(domain);
	}
	
	@Override
	protected String getLabel() {
		return "IP";
	}
	
	@Override
	protected void execute(String site, String url, int group, int index)
			throws IOException {
		fetch(site);
	}
	
	@Override
	protected void onFinish(int group, int total) {
		if (group == total - 1) {
			for (Map.Entry<String, Set<String>> entry : all.entrySet()) {
//				System.out.println("-- " + entry.getKey() + " --");
				String ip = entry.getKey();
				boolean f = false;
				for (String domain : entry.getValue()) {
					String o = IP.get(domain);
					if (o == null || !o.equals(ip)) {
						System.out.println("set(\"" + domain + "\", \"" + entry.getKey() + "\");");
						f = true;
					}
//					System.out.println(domain);
				}
				if (f)
					System.out.println();
			}
		}
	}
}
